package com.yuju.interceptors;

import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.yuju.common.Result;
import com.yuju.common.util.collection.CollectionUtilss;
import com.yuju.log.service.ILogService;
import com.yuju.util.Utils;

/**
 * 
 * 类名：ValidInterceptor  <br />
 *
 * 功能：日志拦截器
 *
 * @author : xuehj <br />
 * @Date : 2017年12月13日 下午5:08:44  <br />
 * @version : 1.1 <br />
 */
public class LogInterceptor implements MethodInterceptor {
	
	@Autowired
	private ILogService logService;
	
	private String[] expertLoginUrl = new String[] {"/wxPay/callback", "/alipay/callback"};

	/**
	 * 
	 * 功能: 拦截所有Controller中的方法<br/>
	 * 判断该次请求有无token参数，并且检查用户是否已登录，
	 * 已登录，则放行，未登录，则提示需要登录
	 * 
	 * 重写：xuehj <br/>
	 * 
	 * @Date ：2017年12月13日 下午5:09:33<br/>
	 * 
	 * @param invocation
	 * @return
	 * @throws Throwable <br/>
	 * @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
	 */
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Method method = invocation.getMethod();
		if (method.getName().equals("intHttpServlet")) {
			return invocation.proceed();
		}
		
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		
		if (Utils.isNotNull(request)) {
			// 获得用户请求的URI
			String path = request.getRequestURI().replace(request.getContextPath(), "");

			if (CollectionUtilss.contains(expertLoginUrl, path)) {
				return invocation.proceed();
			}
		}
		
		Object[] params = invocation.getArguments();
		
		JSONObject obj = null;
		
		if (Utils.isNotNull(params) && params[0] instanceof JSONObject) {
			obj = (JSONObject) params[0];
		}
		
		if (Utils.isNotNull(request)) {
			// 获得用户请求的URI
			String path = request.getRequestURI().replace(request.getContextPath(), "");
			logService.before(path, obj);
		}
		
		Object result = invocation.proceed();
		
		if (result instanceof Result) {
			Result ret = (Result) result; 

			if (ret.getStatus() == -1) {
				return result;
			}
			
			if (Utils.isNotNull(request)) {
				// 获得用户请求的URI
				String path = request.getRequestURI().replace(request.getContextPath(), "");
				logService.handle(path, obj, ret);
			}
		}
		
		return result;
	}

}
